<?php
/**
 *book 公共方法的使用
 */

class pub_mod_book_fun
{
    function __construct()
    {
    }


    //该类参数
    private  static function _cls_params()
    {
        return array(
            'param' => array('openid'=>'oPuLYt8RasQJEihpEE-WSgBdgBh0'),
            'search_url' => 'http://ls.tsdys.com/ArticleList.aspx?',
            'push_url' => 'http://ls.tsdys.com/Push.aspx?',
        );
        //使用//http://ls.tsdys.com/ArticleList.aspx?openid=oPuLYt8RasQJEihpEE-WSgBdgBh0&title=天才在左
    }

    /**
     * 查询网络上的文件
     * @param $keyword
     * @return array|int负数和数组
     */
    public static function get_ansy_search($keyword)
    {
        if(trim($keyword))
        {
            $cls_params = self::_cls_params();
            $parm_url = $cls_params['param'];
            $parm_url['title'] = $keyword;

            $url = $cls_params['search_url'].http_build_query($parm_url) ;
            $html = file_get_contents($url);//如果优化使用crul
            $html = str_replace(array(' ',"\r\n","\n","\t"),'',$html);//不要空格，不要换行，不要tab
            preg_match_all("/(http:\/\/ls.tsdys.com\/Push.aspx\?id=([0-9]{1,10}).*?)>(.*?)<\/a>/", $html, $out);
            /*    0 = array
             *    1 =>array
                      0 => string 'http://ls.tsdys.com/Push.aspx?id=1439873&openId=oPuLYt8RasQJEihpEE-WSgBdgBh0&title=%e5%a4%a9%e6%89%8d%e5%9c%a8%e5%b7%a6"' (length=120)
                      1 => string 'http://ls.tsdys.com/Push.aspx?id=1436837&openId=oPuLYt8RasQJEihpEE-WSgBdgBh0&title=%e5%a4%a9%e6%89%8d%e5%9c%a8%e5%b7%a6"' (length=120)
                                  2 => array
                      0 => string '1439873' (length=7)
                      1 => string '1436837' (length=7)
                                  3 => array
                      0 => string '《天才在左疯子在右》.txt' (length=34)
                      1 => string '天才在左疯子在右.mobi' (length=29)
                 * */

            if(!isset($out[0][0])) return -10002;//没有匹配到,查找不到东西
            foreach($out[1] as $k=>$v)
            { 	
	        $title = str_replace(array('（','）'),array('(',')'),$out[3][$k]);
                $r[] = array('url'=>$out[1][$k],'title'=>$title,'id'=>$out[2][$k]);//不给用户看到真实ID,+998
            }

            return $r;
        }
        else
        {
            return 0;
        }
    }

    /**
     * 请求对方发送email
     * @param $id  对方服务器的id即biao的book_id
     * @return int
     */
    public static function call_send_email($id)
    {
        $cls_params = self::_cls_params();

        $params1['id'] = (int)$id;
        $params1['openId'] = $cls_params['param']['openid'];

        $params['Button1'] = '推送到Kindle';  //不可以少
        $params['stridHidden'] = (int)$id;
        $params['openIdHidden'] = $cls_params['param']['openid'];
        $params['__VIEWSTATE'] = '/wEPDwUJOTAzMDAyNDU5D2QWAgIDD2QWCGYPFgIeB1Zpc2libGVoZAIFDxYCHgtfIUl0ZW1Db3VudGZkAgcPFgIfAGhkAgoPFgIfAGhkZG1UBZjmZ08244RWUkdhOWNgCJsch+pCbMqreu/vMyfN';
        $params['__EVENTVALIDATION'] = '/wEWBAL46eXABgKM54rGBgKdu5rfDwK58/akBLZrH4CzRD61x5HZPsJCBkzMdcrkZNeHGdH7MTozn0NT';

        $ch = curl_init();//初始化curl
        curl_setopt($ch,CURLOPT_URL,$cls_params['push_url'].http_build_query($params1));//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query( $params));//不需要 http_build_url
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        //print_r($data);//输出结果
        if(strpos($data,'Literal1')===false)
        {
            //保存到数据库，该请求发送email的附件不成功。
            return 0;
        }

        return 1;
    }

    /**
     * 定时：去新浪发件箱把附件下载地址保存到数据库。或者被用户触发一次
     *
     */
    public static function save_record_fordb()
    {   
        ///include_once("receivemail.class.php");
        $obj = new receiveMail('whowant2@163.com','ilynobajrbrqptij','','imap.163.com','imap','993', false);
        $obj->connect();

        //循环获取邮件，并处理
        ///require_once './core/init.php';
        $a = self::_loop_email($obj,1,10);
        return $a;
    }

    //死循环
    private  static function _loop_email(&$obj,$page1,$limit10)
    {

        $list = $obj->listMessages($page1,$limit10);//获取邮件


        //当前页需要处理
        if($list['limit']>0)
        {
            if($list['res']) foreach($list['res'] as $k=>$v)
            {
                // file_put_contents(PATH_ROOT.'/log.txt',json_encode($v),FILE_APPEND); print_r(11);exit;
                $tmp_arr = (array)$v;
                $insert_data = array();
                $insert_data['book_name'] = str_replace(array('/',"\\",':','*','?','<','>','|',' '),'',$tmp_arr['subject']);
                $insert_data['is_down'] = 0;
                $insert_data['add_time'] = time();
                $insert_data['book_suffix'] = pathinfo($tmp_arr['subject'],PATHINFO_EXTENSION );
//                $insert_data['book_suffix'] = end(explode('.',$tmp_arr['subject']));
                //$insert_data['book_id'] = isset($_SESSION[$tmp_arr['subject']])?$_SESSION[$tmp_arr['subject']]:0;

                //include_once('../simple_html_dom.php');
                //$html = new simple_html_dom();
                //http://www.cnphp.info/php-simple-html-dom-parser-intro.html');
                //$html->load($tmp_arr['body']);
                //$title = $html->find('dt[title]');
                //$a = $html->find('a');
                //print_r($title);
                //exit;
                //echo $tmp_arr['body'];
                //require_once(PATH_LIBRARY.'/phpQuery.php');
                //print phpQuery::newDocumentHTML($tmp_arr['body'])->find('td[title]');exit;

                preg_match("/<a href=\"(.*?)\".*/", $tmp_arr['body'], $out_arr2);
                preg_match("/<dt title=\"(.*?)\".*/", $tmp_arr['body'], $out_arr3);
                /*array
                  0 => string '<a href="http://preview.mail.163.com/xdownloa
                  1 => string 'http://preview.mail.16 * */ //echo '<pre>'.$tmp_arr['body'];
                $insert_data['caiji_read_email_url'] = $out_arr2[1];//var_dump( $out_arr2);exit;
                $insert_data['caiji_is_call'] = 10;
                if(strpos($insert_data['book_name'],'UTF-8')!==false){
                    $insert_data['book_name'] = str_replace(array('/',"\\",':','*','?','<','>','|',' '),'',$out_arr3[1]);
                    $insert_data['book_suffix'] = pathinfo($out_arr3[1],PATHINFO_EXTENSION );
                }
 


                //if(isset($_SESSION[$insert_data['book_name']]))
                //{
                //$insert_data['book_id'] = $_SESSION[$insert_data['book_name']];
                //    $insert_data['book_type'] = end(explode('.',$insert_data['book_name']));
                //}

                // var_dump($insert_data);exit;

                $exists = db::get_one("select id FROM book where book_name ='{$insert_data['book_name']}' limit 1");
                
                db::insert('dump_msg',array('text'=>$insert_data['book_name']));
                if(!$exists){
                    db::insert('book',$insert_data);
                }
                else
                {
                    db::update('book',$insert_data,'id='.$exists['id'].'');
                }

            }
        }

        //处理完判断是否下一页
        if($list['limit']<$list['total'])
        {
            $page1++;
            return self::_loop_email($obj,$page1,$limit10);
        }

        return 1;

        /*
          'res' =>array(obj,obj2,obj3 );
          'start' => int 1
          'limit' => int 8
          'sorting' => array
              'by' => null
              'direction' => null
          'total' => int 8
          'pages' => float 1

         object(stdClass)[5]
          public 'subject' => string '从0到1:开启商业与未来的秘密.mobi' (length=44)
          public 'from' => string 'whowant2@163.com' (length=16)
          public 'to' => string '79354132@kindle.cn' (length=18)
          public 'date' => string '2 Mar 2016 13:05:22 +0800' (length=25)
          public 'message_id' => string '<56D67494.67F86C.09529@m12-11.163.com>' (length=38)
          public 'size' => int 1401645
          public 'uid' => int 1429794731
          public 'msgno' => int 3
          public 'recent' => int 0
          public 'flagged' => int 0
          public 'answered' => int 0
          public 'deleted' => int 0
          public 'seen' => int 1
          public 'draft' => int 0
          public 'udate' => int 1456895124
          public 'body' => string '<!DOCTYPE html>....'
         * */

    }


    //根据下载书籍
    //$list = db::get_all("select id,down_url,book_name FROM book where is_down=0 order by id desc limit 100");
    public static function down_book_url($list)
    {


        if($list) foreach($list as $k=>$v)
        {
            //$file = file_get_contents($v['down_url']);
            //mb_convert_encoding()
            //iconv("GB2312","UTF-8//TRANSLIT ",$data) ;
            //iconv("GB2312","UTF-8//IGNORE",$data) ;
            //$file =  iconv('GBK',"UTF-8//TRANSLIT ",$file) ;//保存下来的文件是乱码

            $date = date('Y/m');
            $fileName = iconv("utf-8", "gbk", $v['book_name']);///cha ,乱码。
            $save_path_name_gbk = PATH_UPLOADS."/book/{$date}/".$fileName;
            $save_path_name_utf8 = "/book/{$date}/".$v['book_name'];
	    
	    //创建目录-失败
	    $o = util::path_exists(PATH_UPLOADS."/book/{$date}");
	    if(!$o) return 0 ;
	   
            //file_put_contents($save_path_name_gbk,'asdfsadf');

            /*$ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $v['caiji_read_email_url']);
            //curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
            curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,10);
            $txt=curl_exec($ch);*/
            $txt = self::httpcopy($v['caiji_read_email_url'],$save_path_name_gbk );
            $is_down = 0;
            if($txt){
                    $is_down=1;
            }

            if(file_exists($save_path_name_gbk))            {
                db::update('book',array('caiij_ok'=>$is_down,'book_path'=>$save_path_name_utf8)," id='{$v['id']}'");
                //db::query("update book set caiji_is_call=caiji_is_call+1,")
            }

            //return 1;
        }
        return 1;
    }

    private  static function httpcopy($url, $file="", $timeout=60) {
        $file = empty($file) ? pathinfo($url,PATHINFO_BASENAME) : $file;
        $dir = pathinfo($file,PATHINFO_DIRNAME);
        !is_dir($dir) && @mkdir($dir,0755,true);
        $url = str_replace(" ","%20",$url);

        if(function_exists('curl_init')) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($ch,CURLOPT_USERAGENT,"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
            $temp = curl_exec($ch);

            $cut_temp = substr($temp, 0, 10);

            if(stripos($cut_temp,'<!DOCTYPE')!==false)
            {
                preg_match("/<a href=\"(.*?)\".*/", $temp, $out_arr2);
                //var_dump($out_arr2);exit;
                return self::httpcopy($out_arr2[1],$file );
            }

            if(file_put_contents($file, $temp) && !curl_error($ch)) {
                return $file;
            } else {
                return false;
            }
        } else {
            $opts = array(
                "http"=>array(
                    "method"=>"GET",
                    "header"=>"",
                    "timeout"=>$timeout)
            );
            $context = stream_context_create($opts);
            if(@copy($url, $file, $context)) {
                //$http_response_header
                return $file;
            } else {
                return false;
            }
        }
    }
}
